<template>
  <el-drawer title="角色权限设置" v-model="visible" size="50%" destroy-on-close @closed="emit('closed')">
    <el-tabs tab-position="top" style="margin: 20px">
      <el-tab-pane label="菜单权限">
        <el-tree ref="menuRef" node-key="uuid" default-expand-all :data="menu.list" :props="menu.props"
                 show-checkbox></el-tree>
      </el-tab-pane>
      <el-tab-pane label="数据权限">
        <el-tree ref="apiRef" node-key="uuid" :data="api.list" :props="api.props" show-checkbox>
        </el-tree>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="visible=false">取 消</el-button>
      <el-button type="primary" :loading="isSave" @click="submit()">保 存</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import {nextTick, onMounted, reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import Apis from '@/api'

const emit = defineEmits(['success', 'closed'])

const props = defineProps({
  roleCode: {
    type: String,
    default: ""
  }
})

let menuRef = ref()
let apiRef = ref()

let visible = ref(false)
let isSave = ref(false)
let menu = reactive({
  list: [],
  checked: [],
  props: {
    label: (data) => {
      return data.meta.title
    }
  }
})
let api = reactive({
  list: [],
  checked: [],
  props: {
    label: (data) => {
      return data.apiDescription
    }
  }
},)

let dashboard = ref("0")

onMounted(() => {
  getPermission()
})


const open = () => {
  visible.value = true;
}
const submit = async () => {
  isSave.value = true;
  //选中的和半选的合并后传值接口
  let checkedMenuKeys = menuRef.value.getCheckedKeys().concat(menuRef.value.getHalfCheckedKeys())
  let checkedApiKeys = apiRef.value.getCheckedKeys().concat(apiRef.value.getHalfCheckedKeys())

  isSave.value = true
  let res = await Apis.api_setting.role.permission_update.post({
    authMenu: checkedMenuKeys,
    authApi: checkedApiKeys,
    roleCode: props.roleCode,
  })
  isSave.value = false
  if (res.code === 0) {
    ElMessage.success("权限变更成功")
  } else {
    ElMessage.error(res.message)
  }
}
const getPermission = async () => {
  let res = await Apis.api_setting.role.permission_list.get({roleCode: props.roleCode});
  if (res.code === 0) {
    // 使用 Object.assign 确保响应式更新
    Object.assign(menu.list, res.data.allMenu)
    Object.assign(api.list, res.data.allApi)
    // 获取接口返回的之前选中的和半选的合并，处理过滤掉有叶子节点的key
    menu.checked = res.data.authMenu
    api.checked = res.data.authApi
    await nextTick(() => {
      let filterMenuKeys = menu.checked.filter(key => menuRef.value.getNode(key)?.isLeaf)
      menuRef.value.setCheckedKeys(filterMenuKeys, true)
      let filterApiKeys = api.checked.filter(key => apiRef.value.getNode(key)?.isLeaf)
      apiRef.value.setCheckedKeys(filterApiKeys, true)
    })
  } else {
    ElMessage.error(res.message)
  }
}
defineExpose({
  open
})
</script>

<style scoped>
.treeMain {
  height: 280px;
  overflow: auto;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
}
</style>
